package com.wxh.lock;

import java.util.concurrent.Semaphore;

/**
 * @ClassName: TestSemaphore
 * @Description: 信号量
 * @Author wxh
 * @Date: 2022/2/10 9:08
 * @Version V1.0.0
 * @Since 1.8
 */
public class TestSemaphore {
    /**
     * 如果Semaphore的数值被初始化为1，那么一个线程就可以通过acquire进入互斥状态
     * @param args
     */
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 8; i++) {
            new Worker(i, semaphore).start();
        }
    }

    static class Worker extends Thread{
        private int num;
        private Semaphore semaphore;

        public Worker(int num, Semaphore semaphore){
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                // 抢许可
                semaphore.acquire();
                Thread.sleep(2000);
                // 释放许可
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
